// 用户相关路由
import { Router } from 'express'
import Joi from 'joi'
import { prisma } from '../lib/prisma'
import { CacheManager } from '../lib/memory-cache'
import { asyncHandler, createError } from '../middleware/error-handler'
import { authenticate } from '../middleware/auth'

const router = Router()

// 所有路由都需要认证
router.use(authenticate)

// 验证模式
const updateProfileSchema = Joi.object({
  nickname: Joi.string().max(50).optional().messages({
    'string.max': '昵称不能超过50个字符'
  }),
  avatarUrl: Joi.string().uri().optional().messages({
    'string.uri': '头像URL格式不正确'
  })
})

const updateSettingsSchema = Joi.object({
  theme: Joi.string().valid('LIGHT', 'DARK', 'AUTO').optional(),
  searchEngine: Joi.string().valid('GOOGLE', 'BING', 'BAIDU', 'DUCKDUCKGO').optional(),
  backgroundType: Joi.string().valid('GRADIENT', 'IMAGE', 'COLOR').optional(),
  backgroundValue: Joi.string().max(500).optional().allow('').messages({
    'string.max': '背景值不能超过500个字符'
  }),
  showBookmarks: Joi.boolean().optional(),
  showWeather: Joi.boolean().optional(),
  showTime: Joi.boolean().optional(),
  language: Joi.string().max(10).optional().messages({
    'string.max': '语言代码不能超过10个字符'
  })
})

// 获取用户资料
router.get('/profile', asyncHandler(async (req, res) => {
  const userId = req.user!.id
  
  // 尝试从缓存获取
  const cacheKey = CacheManager.getUserCacheKey(userId, 'profile')
  let profile = await CacheManager.get(cacheKey)
  
  if (!profile) {
    profile = await prisma.userProfile.findUnique({
      where: { userId },
      select: {
        id: true,
        nickname: true,
        avatarUrl: true,
        createdAt: true,
        updatedAt: true
      }
    })
    
    if (profile) {
      // 缓存10分钟
      await CacheManager.set(cacheKey, profile, 600)
    }
  }

  if (!profile) {
    throw createError.notFound('用户资料不存在')
  }

  res.json({
    profile
  })
}))

// 更新用户资料
router.put('/profile', asyncHandler(async (req, res) => {
  // 验证请求数据
  const { error, value } = updateProfileSchema.validate(req.body)
  if (error) {
    throw createError.badRequest(error.details[0].message)
  }

  const userId = req.user!.id
  const updates = value

  // 更新用户资料
  const updatedProfile = await prisma.userProfile.update({
    where: { userId },
    data: {
      ...updates,
      updatedAt: new Date()
    },
    select: {
      id: true,
      nickname: true,
      avatarUrl: true,
      createdAt: true,
      updatedAt: true
    }
  })

  // 清除相关缓存
  await CacheManager.del(CacheManager.getUserCacheKey(userId, 'profile'))
  await CacheManager.del(CacheManager.getUserCacheKey(userId, 'info'))

  res.json({
    message: '资料更新成功',
    profile: updatedProfile
  })
}))

// 获取用户设置
router.get('/settings', asyncHandler(async (req, res) => {
  const userId = req.user!.id
  
  // 尝试从缓存获取
  const cacheKey = CacheManager.getUserCacheKey(userId, 'settings')
  let settings = await CacheManager.get(cacheKey)
  
  if (!settings) {
    settings = await prisma.userSettings.findUnique({
      where: { userId },
      select: {
        id: true,
        theme: true,
        searchEngine: true,
        backgroundType: true,
        backgroundValue: true,
        showBookmarks: true,
        showWeather: true,
        showTime: true,
        language: true,
        createdAt: true,
        updatedAt: true
      }
    })
    
    if (settings) {
      // 缓存10分钟
      await CacheManager.set(cacheKey, settings, 600)
    }
  }

  if (!settings) {
    throw createError.notFound('用户设置不存在')
  }

  res.json({
    settings
  })
}))

// 更新用户设置
router.put('/settings', asyncHandler(async (req, res) => {
  // 验证请求数据
  const { error, value } = updateSettingsSchema.validate(req.body)
  if (error) {
    throw createError.badRequest(error.details[0].message)
  }

  const userId = req.user!.id
  const updates = value

  // 更新用户设置
  const updatedSettings = await prisma.userSettings.update({
    where: { userId },
    data: {
      ...updates,
      updatedAt: new Date()
    },
    select: {
      id: true,
      theme: true,
      searchEngine: true,
      backgroundType: true,
      backgroundValue: true,
      showBookmarks: true,
      showWeather: true,
      showTime: true,
      language: true,
      createdAt: true,
      updatedAt: true
    }
  })

  // 清除相关缓存
  await CacheManager.del(CacheManager.getUserCacheKey(userId, 'settings'))
  await CacheManager.del(CacheManager.getUserCacheKey(userId, 'info'))

  res.json({
    message: '设置更新成功',
    settings: updatedSettings
  })
}))

// 批量获取用户数据（优化版本）
router.get('/data', asyncHandler(async (req, res) => {
  const userId = req.user!.id
  
  // 尝试从缓存获取完整用户数据
  const cacheKey = CacheManager.getUserCacheKey(userId, 'complete')
  let userData = await CacheManager.get(cacheKey)
  
  if (!userData) {
    // 并行查询用户资料和设置
    const [profile, settings] = await Promise.all([
      prisma.userProfile.findUnique({
        where: { userId },
        select: {
          id: true,
          nickname: true,
          avatarUrl: true,
          createdAt: true,
          updatedAt: true
        }
      }),
      prisma.userSettings.findUnique({
        where: { userId },
        select: {
          id: true,
          theme: true,
          searchEngine: true,
          backgroundType: true,
          backgroundValue: true,
          showBookmarks: true,
          showWeather: true,
          showTime: true,
          language: true,
          createdAt: true,
          updatedAt: true
        }
      })
    ])
    
    userData = { profile, settings }
    
    // 缓存5分钟
    await CacheManager.set(cacheKey, userData, 300)
  }

  res.json(userData)
}))

// 获取用户统计信息
router.get('/stats', asyncHandler(async (req, res) => {
  const userId = req.user!.id
  
  // 尝试从缓存获取
  const cacheKey = CacheManager.getUserCacheKey(userId, 'stats')
  let stats = await CacheManager.get(cacheKey)
  
  if (!stats) {
    // 并行查询各种统计数据
    const [bookmarkCount, user] = await Promise.all([
      prisma.bookmark.count({
        where: { userId }
      }),
      prisma.user.findUnique({
        where: { id: userId },
        select: {
          createdAt: true
        }
      })
    ])
    
    stats = {
      bookmarkCount,
      memberSince: user?.createdAt,
      lastUpdated: new Date()
    }
    
    // 缓存15分钟
    await CacheManager.set(cacheKey, stats, 900)
  }

  res.json({
    stats
  })
}))

// 删除用户账户
router.delete('/account', asyncHandler(async (req, res) => {
  const userId = req.user!.id
  
  // 删除用户（级联删除相关数据）
  await prisma.user.delete({
    where: { id: userId }
  })
  
  // 清除所有相关缓存
  await CacheManager.clearUserCache(userId)
  
  res.json({
    message: '账户删除成功'
  })
}))

export { router as userRoutes }